package com.lym.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lym.reggie.common.BaseContext;
import com.lym.reggie.common.CustomException;
import com.lym.reggie.entity.*;
import com.lym.reggie.mapper.OrdersMapper;
import com.lym.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;

    //支付
    @Override
    public void submit(Orders orders) {
        //remark payMethod addressBookid
        Long userId = BaseContext.getCurrentId();

        //1。向订单表中插入数据 一条数据

        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);

        //用户名、手机号
        User user = userService.getById(userId);
        if (user.getName()!=null){
            orders.setUserName(user.getName());
        }
        orders.setPhone(user.getPhone());
        //地址、收货人
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook==null){
            throw new CustomException("地址信息有误,不能下单");
        }
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setConsignee(addressBook.getConsignee());
        //计算金额   获取该用户购物车中的商品，价钱=单价*个数并相加   怎样计算?
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId!=null,ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper);
        if (shoppingCartList==null || shoppingCartList.size()==0){
            throw new CustomException("购物车为空不能下单！");
        }
        Long orderId = IdWorker.getId();//使用工具生成订单号
        orders.setId(orderId);

        AtomicInteger amount = new AtomicInteger(0);//原子整数类，保证线程安全。一个提供原子操作的Integer的类。在Java语言中，++i和i++操作并不是线程安全的，在使用的时候，不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(item->{
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());//单份的金额

            return orderDetail;
        }).collect(Collectors.toList());
        orders.setAmount(new BigDecimal(amount.get()));

        this.save(orders);

        //2。向订单明细表插入数据 多条数据
        orderDetailService.saveBatch(orderDetailList);
        //3。清空购物车
        //清空购物车数据  wrapper封装了userId我们直接使用这个条件来进行删除就行
        shoppingCartService.remove(wrapper);
    }

    //查询该用户的所有订单
    @Override
    public Page getUserPage(int page, int pageSize) {

        Page<Orders> pageInfo = new Page(page,pageSize);
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getOrderTime);//添加排序条件，根据更新时间降序排列
        wrapper.eq(userId!=null,Orders::getUserId,userId);
        //这里是直接把当前用户分页的全部结果查询出来，要添加用户id作为查询条件，否则会出现用户可以查询到其他用户的订单情况
        this.page(pageInfo,wrapper);

        //1。对OrderDto进行需要的属性赋值
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> recordsOrdersDto = records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();//此时的orderDto对象里面orderDetails属性还是空 下面准备为它赋值

            //通过OrderId查询对应的OrderDetail
            Long orderId = orders.getId();
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            //根据订单id获取orderDetails
            queryWrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper);

            //拷贝orders属性到ordersDto
            BeanUtils.copyProperties(orders,ordersDto);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());

        //2。拷贝
        Page<OrdersDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        dtoPage.setRecords(recordsOrdersDto);

        return dtoPage;

    }

    //再来一单
    @Override
    public void again(long orderId) {
        //清除购物车数据、添加此订单中的数据
        Long userId = BaseContext.getCurrentId();
        // 1。清除购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId!=null,ShoppingCart::getUserId,userId);
        shoppingCartService.remove(wrapper);

        //2.添加此订单ID的所有商品及details到购物车中
        //2.1 根据orderId获取details
        LambdaQueryWrapper<OrderDetail> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(OrderDetail::getOrderId,orderId);
        List<OrderDetail> orderDetails = orderDetailService.list(wrapper2);

        List<ShoppingCart> shoppingCartList = orderDetails.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            BeanUtils.copyProperties(orderDetail,shoppingCart,"id");

            shoppingCart.setUserId(userId);
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCartList);
    }
}
